package com.yeskery.nut.extend.oauth;

import com.yeskery.nut.application.ApplicationType;
import com.yeskery.nut.application.ServerEventContext;
import com.yeskery.nut.bean.BeanRegister;
import com.yeskery.nut.core.ControllerManager;
import com.yeskery.nut.plugin.ApplicationContextSupportBasePlugin;
import com.yeskery.nut.plugin.PluginBeanMetadata;
import com.yeskery.nut.plugin.ServerEventPlugin;

import java.util.Collection;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * OAuth2服务器插件
 * @author YESKERY
 * 2024/10/21
 */
public class OAuth2ServerPlugin extends ApplicationContextSupportBasePlugin implements ServerEventPlugin {

    /** 授权请求参数key */
    public static final String AUTHORIZE_REQUEST_PARAMS_KEY = "com.yeskery.nut.extend.oauth.OAuthPlugin.authorize.request";

    /** 授权码参数key */
    public static final String AUTHORIZE_REQUEST_CODE_VALUE_KEY = "com.yeskery.nut.extend.oauth.OAuthPlugin.authorize.code.value";

    /** 控制器管理器消费 */
    private Consumer<ControllerManager> controllerManagerConsumer;

    /** 要绑定的bean元数据 */
    private Collection<PluginBeanMetadata> bindPluginBeanMetadata;

    @Override
    protected Collection<PluginBeanMetadata> getRegisterPluginBeanMetadata() {
        if (bindPluginBeanMetadata != null && !bindPluginBeanMetadata.isEmpty()) {
            return bindPluginBeanMetadata.stream().filter(r -> !((BeanRegister) getApplicationContext()).containBean(r.getBeanName())).collect(Collectors.toSet());
        }
        return super.getRegisterPluginBeanMetadata();
    }

    @Override
    public void beforeStart(ServerEventContext serverEventContext) {
        ApplicationType applicationType = serverEventContext.getApplicationMetadata().getApplicationType();
        if (ApplicationType.isWebApplicationType(applicationType) && controllerManagerConsumer != null) {
            controllerManagerConsumer.accept(serverEventContext.getControllerManager());
        }
    }

    /**
     * 设置控制器管理器消费
     * @param controllerManagerConsumer 控制器管理器消费
     */
    public void setControllerManagerConsumer(Consumer<ControllerManager> controllerManagerConsumer) {
        this.controllerManagerConsumer = controllerManagerConsumer;
    }

    /**
     * 设置要绑定的bean元数据
     * @param bindPluginBeanMetadata 要绑定的bean元数据
     */
    public void setBindPluginBeanMetadata(Collection<PluginBeanMetadata> bindPluginBeanMetadata) {
        this.bindPluginBeanMetadata = bindPluginBeanMetadata;
    }
}
